<?php

namespace App\Http\Controllers\Third;

use App\Http\Classes\User;
use Illuminate\Http\Request;
use App\Http\Classes\SaeTOAuthV2;
use App\Http\Controllers\Controller;
use App\Http\Classes\OAuthException;
use App\Http\Classes\SaeTClientV2;

class WeiboController extends Controller
{
    public function authWeibo()
    {
        try
        {
            $a = new SaeTOAuthV2( WB_AKEY, WB_SKEY);
            $url = $a->getAuthorizeURL( WB_CALLBACK_URL );
            return redirect($url);
//            $a = new \SaeTOAuthV2()
//            $o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
//
//$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    public function loginCallback(Request $request)
    {
        try {

            $o = new SaeTOAuthV2(WB_AKEY, WB_SKEY);
            $token = null;
            if (isset($_REQUEST['code'])) {
                $keys = array();
                $keys['code'] = $_REQUEST['code'];
                $keys['redirect_uri'] = WB_CALLBACK_URL;

                $token = $o->getAccessToken('code', $keys);

            }
            else
            {
                return redirect('login.html');
            }
            if ($token) {
                setcookie('weibojs_' . $o->client_id, http_build_query($token));
                $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $token['access_token'] );
                $ms  = $c->home_timeline(); // done
                $uid_get = $c->get_uid();
                $uid = $uid_get['uid'];
                $user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息

                $user = new User();

                $userInfo = $user->loginByWeibo($user_message['id']);

                if ( $userInfo )
                {
                    setcookie('USER_ID', $userInfo->id, time() + DAY7, '/' );
                    setcookie('USER_TOKEN', $userInfo->token, time() + DAY7, '/' );
                    setcookie('userInfo', json_encode($userInfo), time() + DAY7, '/' );
                    return redirect('home.html');
                }
                else
                {
                    return view('front.weiboCallback')->with('weibo', $user_message);
                }

            }
            else
            {
                return redirect('login.html');
            }

            //dd($user_message);
        }
        catch (\Exception $exception)
        {
            return $this->exceptionResponse($exception, __FUNCTION__);
        }
    }

    public function info(){
        $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
        $ms  = $c->home_timeline(); // done
        $uid_get = $c->get_uid();
        $uid = $uid_get['uid'];
        $user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
        dd($user_message);
    }
}
